const User = require('../db/sequelize/model/User');
const Task = require('../db/sequelize/model/Task');

async function createTask(userId, content, remindTime) {
  const user = await User.findByPk(userId);
  const newTask = await user.createTask({
    content,
    remindTime
  });

  return { id: newTask.dataValues.id };
}

async function getTaskById(taskId) {
  const task = await Task.findByPk(taskId, {
    attributes: ['id', 'content', 'remindTime', 'isCompleted', 'createdAt', 'updatedAt']
  });
  return task.dataValues;
}

async function getTasks(userId, { sort = 'createdAt', order = 'DESC', ...conditions }) {
  const user = await User.findByPk(userId);
  const tasks = await user.getTasks({
    where: conditions,
    attributes: ['id', 'content', 'remindTime', 'isCompleted', 'createdAt', 'updatedAt'],
    order: [[sort, order]]
  });
  return tasks.map(task => task.dataValues);
}

async function updateTask(userId, taskId, content, isCompleted, remindTime) {
  const user = await User.findByPk(userId);
  const task = await Task.findByPk(taskId);
  if (!task || !(await user.hasTask(task))) {
    return;
  }
  const updateData = {};
  if (content) {
    updateData.content = content;
  }
  if (isCompleted !== undefined) {
    if (isCompleted) {
      remindTime = null;
    }
    updateData.isCompleted = isCompleted;
  }
  if (remindTime !== undefined) {
    updateData.remindTime = remindTime;
  }
  return await task.update(updateData);
}

async function deleteTask(userId, taskId) {
  const user = await User.findByPk(userId);
  const task = await Task.findByPk(taskId);
  if (!(await user.hasTask(task))) {
    return;
  }
  await task.update({ remindTime: null });
  return await task.destroy();
}

module.exports = {
  createTask,
  getTaskById,
  getTasks,
  updateTask,
  deleteTask
};
